<template>
  <section class="todoapp">
    <!-- 头部部分 -->
    <TodoListHearder @contentPut="contentPut"></TodoListHearder>

    <!-- 主体部分 -->
    <TodoListBody :list="typeList" @listFlag="listFlag" @del="del" @changeAll="changeAll"></TodoListBody>
    <!-- 底部部分 -->
    <TodoListFooter
      :showFlag="showFlag"
      :sum="sum"
      @clearBtn="clearBtn"
      :type="type"
      @changeType="changeType"
    ></TodoListFooter>
  </section>
</template>

<script>
import TodoListHearder from './components/TodoListHearder.vue'
import TodoListBody from './components/TodoListBody.vue'
import TodoListFooter from './components/TodoListFooter.vue'
export default {
  components: {
    TodoListHearder,
    TodoListBody,
    TodoListFooter,
  },
  data() {
    return {
      list:JSON.parse(localStorage.getItem('list'))|| [
        { id: 1, content: '读万卷书', flag: true },
        { id: 2, content: '行万里路', flag: false },
      ],
      type: 'all',
    }
  },
  methods: {
    listFlag(id, flag) {
      this.list.forEach((item) => {
        if (item.id === id) {
          item.flag = flag
        }
      })
    },
    contentPut(value) {
      this.list = [
        ...this.list,
        { id: +new Date(), content: value, flag: false },
      ]
    },
    clearBtn() {
      this.list = this.list.filter((item) => !item.flag)
    },
    del(id, flag) {
      if (!flag) {
        return alert('未完成不能删除')
      }
      this.list = this.list.filter((item) => item.id !== id)
    },
    changeType(value) {
      this.type = value
    },
       changeAll(){
      this.list.forEach(item=> item.flag=true)
    },
  },
  computed: {
    showFlag() {
      return this.list.some((item) => item.flag)
    },
    sum() {
      return this.list.filter((item) => !item.flag).length
    },
    typeList() {
      switch (this.type) {
        case 'all':
          return this.list
        case 'active':
          return this.list.filter(item=>!item.flag)
        case 'completed':
          return this.list.filter(item=>item.flag)
        default:
          return this.list
      }
    },
    
  },
  watch:{
    list:{
      deep:true,
      handler(nv){
        localStorage.setItem('list',JSON.stringify(nv))
      }
    }
  }
}
</script>

<style></style>
